package p8.code;

/**
 * 锁分段示例学习
 */
public class StripedMap {

    // 同步策略：buckets[n]由locks[n%N_LOCKS]来保护
    private static final int N_LOCKS = 16;
    private final Node[] buckets;
    private final Object[] locks;

    private static class Node{
        Object key;
        Object value;
        Node next;
    }

    public StripedMap(int numBuckets) {
        this.buckets = new Node[numBuckets];
        locks = new Object[N_LOCKS];
        for(int i=0;i<N_LOCKS;i++){
            locks[i] = new Object();
        }
    }

    private final int hash(Object key) {
        return Math.abs(key.hashCode()%buckets.length);
    }

    public Object get(Object key) {
        int index = hash(key);
        // 获取保护的锁
        synchronized (locks[index%N_LOCKS]){
            for(Node m = buckets[index];m!=null;m = m.next){
                if(m.key.equals(key))
                    return m.value;
            }
        }
        return null;
    }

    public void clear() {
        for(int i = 0;i < buckets.length; i++){
            synchronized (locks[i % N_LOCKS]) {
                buckets[i] = null;
            }
        }
    }

}
